<template>
  <div class="container">
    <div class="handle-box">
      <el-row :gutter="25">
        <el-col :span="8">
          <el-form ref="form" :model="form" label-width="120px">
            <el-form-item label="账户名称：">
              <el-input
                v-model="select.name"
                placeholder="请输入名称"
                class="handle-input mr10"
              ></el-input>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="10">
          <el-form ref="form" :model="form" style="float: left">
            <el-form-item>
              <el-button type="primary" size="mini" icon="el-icon-search" @click="screeningData"
                >查询</el-button
              >
              <el-button type="success" size="mini" icon="el-icon-plus" @click="handleAdd"
                >新增</el-button
              >
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </div>
    <el-table
      highlight-current-row
      :data="
        tableData.slice((currentPage - 1) * pageSize, currentPage * pageSize)
      "
    >
      <!-- <el-table-column type="index" :index="indexMethod" label="ID"></el-table-column> -->
      <el-table-column prop="REMARK" label="账户名称"></el-table-column>
      <el-table-column prop="USERNAME" label="组织机构名称"></el-table-column>
      <el-table-column prop="ROLE_NAME" label="所属角色"></el-table-column>
      <!-- <el-table-column prop="CLIENT_NO" label="上级组织机构"></el-table-column> -->
      <el-table-column prop="UID" label="登录ID"></el-table-column>
      <el-table-column prop="PWD" label="登录密码"></el-table-column>
      <el-table-column label="操作" width="180">
        <template slot-scope="scope">
          <el-button type="text" @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-button
            type="text"
            @click="handleDelete(scope.$index, scope.row)"
            style="color: red"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="tableData.length"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      ></el-pagination>
    </div>
    <!-- 弹出框 -->
    <el-dialog
      :title="editDialogTitle"
      :visible.sync="isVisibleEdit"
      width="50%"
    >
      <el-form ref="form" :model="form" label-width="100px" class="flex">
        <el-form-item label="账户名称：" class="wid50">
          <el-input
            v-model="form.REMARK"
            placeholder="请输入账户名称"
            class="handle-input mr10"
          ></el-input>
        </el-form-item>
        <el-form-item label="角色名称：" class="wid50">
          <el-select v-model="form.ROLE_ID" placeholder="请选择">
            <el-option
              v-for="(item, index) in selectRoleInfoList"
              :key="index"
              :label="item.NAME"
              :value="item.ID"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="组织级别：" class="wid50">
          <el-select
            v-model="form.CTYPE"
            placeholder="请选择"
            @change="changClient"
          >
            <el-option
              v-for="item in rolelevel"
              :key="item.rolelevelindex"
              :label="item.roleleveltitle"
              :value="item.rolelevelindex"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="组织机构：" class="wid50">
          <el-select
            v-model="form.CLIENT_NO_select"
            value-key="id"
            placeholder="请选择"
            @change="$forceUpdate()"
          >
            <el-option
              v-for="item in selectClientInfoList"
              :key="item.CLIENT_NO"
              :label="item.CLIENT_NAME"
              date-name="item.CLIENT_NAME"
              :value="item.CLIENT_NO"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="原始账号：" class="wid50" v-if="idEdit">
          <el-input
            disabled="true"
            v-model="form.UID"
            placeholder="请输入账号"
            class="handle-input mr10"
          ></el-input>
        </el-form-item>
        <el-form-item label="登陆账号：" class="wid50">
          <el-input
            v-model="form.newUID"
            placeholder="请输入账号"
            class="handle-input mr10"
            @input="change($event)"
          ></el-input>
        </el-form-item>
        <el-form-item label="绑定密码：" class="wid50">
          <el-input
            v-model="form.PWD"
            placeholder="请输入密码"
            class="handle-input mr10"
            show-password
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isVisibleEdit = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>

import '../../assets/css/common.css'

export default {
  data () {
    return {
      currentPage: 1, //初始页
      pageSize: 10,    //    每页的数据
      originalData: [],
      tableData: [],
      editDialogTitle: '',
      isVisibleEdit: false,
      form: {},
      selectRoleInfoList: [],
      selectClientInfoList: [],
      select: {
        name: ''
      },
      rolelevel: [{
        roleleveltitle: '公司',
        rolelevelindex: '-1'
      }, {
        roleleveltitle: '项目',
        rolelevelindex: '0'
      }, {
        roleleveltitle: '机扫',
        rolelevelindex: '1'
      }, {
        roleleveltitle: '垃圾',
        rolelevelindex: '2'
      }, {
        roleleveltitle: '人工',
        rolelevelindex: '3'
      }, {
        roleleveltitle: '公厕维保',
        rolelevelindex: '4'
      }],
    }
  },
  created () {
    if (localStorage.getItem('CTYPE') == '0') {
      this.rolelevel.shift()
    } else if (localStorage.getItem('CTYPE') != '-1') {
      this.rolelevel = []
    }
    this.getTrackUserInfoList();
    this.getRoleInfolist()
    this.getClientRoleList()
  },
  methods: {
    async getTrackUserInfoList () {
      // var url = 'Role/GetTrackUserInfoList?ClientNo=' + localStorage.getItem('CLIENT_NO_LOGIN')
      var url = 'Role/GetTrackUserInfoListByUID?UID=' + localStorage.getItem('LOGIN_NAME')
      const { data } = await this.$Http.get(url)
      this.originalData = data
      console.log("角色"+localStorage.getItem('LOGIN_NAME'))
      this.screeningData()
    },
    // 角色下拉列表
    async getRoleInfolist () {
      var url = 'Role/GetRoleInfoListByUserID?UID=' + localStorage.getItem('LOGIN_NAME')
      const { data } = await this.$Http.get(url)
      this.selectRoleInfoList = data
      console.log("角色"+localStorage.getItem('LOGIN_NAME'))
    },
    // 获取组织机构名
    async getClientRoleList (cytpe) {
      const params = {
        // 加上编辑功能的时候需要判断一下
        ClientNo: localStorage.getItem('CLIENT_NO_LOGIN'),
        CTYPE: cytpe,
      }
      const { data } = await this.$Http.get('Role/getClientRoleList', { params })
      this.selectClientInfoList = data
    },
    // 给组织机构名称下拉列表传值
    changClient (e) {
      this.form.CLIENT_NO_select = ''
      this.getClientRoleList(e)
    },
    // 打开新增窗口
    handleAdd () {
      this.editDialogTitle = '新增账户'
      //清空编辑框
      this.form = {}
      //展示窗口
      this.isVisibleEdit = true;
      this.idEdit = false;
    },
    // 打开编辑窗口
    handleEdit (index, row) {
      // this.form = row;
      this.form = Object.assign({}, row);
      // {"UID":"ZFadmin","PWD":"123456","USERNAME":"城管委项目","CLIENT_NO":"00000","CTYPE":"-1",
      // "ROLE_ID":"17","ROLE_NAME":"城管委总管理员","REMARK":"东丽区"}
      this.form.CLIENT_NO_select = this.form.USERNAME
      this.form.newUID = this.form.UID
      this.getClientRoleList(this.form.CTYPE)
      this.editDialogTitle = '编辑账户'
      this.isVisibleEdit = true;
      this.idEdit = true;
    },
    // 点击保存，判断是新增还是编辑操作
    handleSubmit () {
      if (this.editDialogTitle == '新增账户') {
        this.saveAdd()
      } else {
        this.saveEdit()
      }
    },
    // 新增保存
    async saveAdd () {
      let clientName = this.selectClientInfoList.find(val => val.CLIENT_NO == this.form.CLIENT_NO_select).CLIENT_NAME
      const params = {
        user: this.form.newUID,
        password: this.form.PWD,
        CLIENTNAME: clientName,
        CTYPE: this.form.CTYPE,
        ROLEID: this.form.ROLE_ID,
        REMARK: this.form.REMARK,
      }
      console.log('新增账号参数：')
      console.log(params)
      const { data } = await this.$Http.get('Role/AddTrackUserInfo', { params })
      if (data.IsSucess) {
        this.$message.success('新增成功')
        this.isVisibleEdit = false
        this.getTrackUserInfoList()
      } else {
        if (data.Message === 'NameRepeat') {
          this.$message.error('此登陆账号已存在，请重新填入未使用的登陆账号')
        }
      }
    },
    // 保存编辑
    async saveEdit () {
      let clientNo = ''
      let clientName = ''
      if (this.form.CLIENT_NO_select === this.form.USERNAME) {
        //未做选择修改
        clientNo = this.form.CLIENT_NO
        clientName = this.form.USERNAME
      } else {
        clientNo = this.form.CLIENT_NO_select
        clientName = this.selectClientInfoList.find(val => val.CLIENT_NO == this.form.CLIENT_NO_select).CLIENT_NAME
      }
      // let clientName = this.selectClientInfoList.find(val => val.CLIENT_NO == this.form.CLIENT_NO_select).CLIENT_NAME
      if (this.form.newUID === this.form.UID) {
        this.form.newUID = ''
      }
      console.log(this.form)
      const params = {
        userOLD: this.form.UID,
        userNEW: this.form.newUID,
        password: this.form.PWD,
        CLIENT_NO: clientNo,
        CLIENT_NAME: clientName,
        CTYPE: this.form.CTYPE,
        ROLEID: this.form.ROLE_ID,
        REMARK: this.form.REMARK,
      }
      console.log('编辑账号参数：')
      console.log(params)
      const { data } = await this.$Http.get('Role/UpdataTrackUserInfo', { params })
      if (data.IsSucess) {
        this.$message.success('编辑成功')
        this.isVisibleEdit = false
        this.getTrackUserInfoList()
      } else {
        if (data.Message === 'NameRepeat') {
          this.$message.error('新登陆账号已存在，请重新填入未使用的登陆账号')
        }
      }
    },
    // 删除账户
    async handleDelete (index, row) {
      const confirmResult = await this.$confirm('确定删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult == 'confirm') {
        const params = {
          user: row.UID,
        }
        const { data } = await this.$Http.get('Role/DeletedTrackUserInfo', { params })
        if (data.IsSucess) {
          this.$message.success('删除成功')
          this.isVisibleEdit = false
          this.getTrackUserInfoList()
        }else {
            this.$message.error('删除失败');
          }
      }else{
        this.$message.info('取消删除')
        this.isVisibleEdit = false
      }
    },
    // 模糊查询
    screeningData () {
      this.currentPage = 1
      this.tableData = this.originalData
      if (this.select.name) this.tableData = this.tableData.filter(item => item.REMARK.includes(this.select.name))
    },
    // mohu () {
    //   var search = this.select.name;
    //   console.log(search)
    //   var newdate = [];
    //   if (search) {
    //     this.tableData.filter(item => {
    //       console.log(item)
    //       if (item.USERNAME.includes(search)) {
    //         console.log(item)
    //         newdate.push(item)
    //       }
    //     })
    //   } else if (search == '') {
    //     // alert('空')
    //     // this.getrolelist()
    //   }
    //   this.tableData = newdate
    // },
    change (e) {
      this.$forceUpdate()
    },
    // 分页导航
    handlePageChange (currentPage) {
      this.currentPage = currentPage;
      // this.$set(this.query, 'pageIndex', val);
      // this.getData();
    },
    handleSizeChange (size) {
      this.pageSize = size;
    },
  }
}
</script>
<style scoped>
.el-select {
  width: 100%;
  max-width: 200px;
}
.el-input {
  width: 100%;
  max-width: 200px;
}
/* .displaynone {
  display: block;
}
.displaytnone {
  display: block;
}
.displayenone {
  display: block;
}
.displayfnone {
  display: block;
} */
</style>